package com.tonglin.red.service.impl;

import com.tonglin.red.entity.Detail;
import com.tonglin.red.entity.Record;
import com.tonglin.red.entity.RobRecord;
import com.tonglin.red.entity.vo.RedPacketDto;
import com.tonglin.red.mapper.DetailMapper;
import com.tonglin.red.mapper.RecordMapper;
import com.tonglin.red.mapper.RobRecordMapper;
import com.tonglin.red.service.IRedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 将红包信息放到数据库
 */
@Service
public class IRedServiceImpl implements IRedService {
    //日志
    private static final Logger log = LoggerFactory.getLogger(IRedServiceImpl.class);
    //发红包时全局唯一标识串操作接口mapper
    @Autowired
    RecordMapper recordMapper;
    //发红包时随机数算法生成的随机金额列表等信息操作接口mapper
    @Autowired
    DetailMapper detailMapper;
    @Autowired
    private  RobRecordMapper robRecordMapper;
    @Override
    @Async
    @Transactional(rollbackFor = Exception.class)
    public void recordRedPacket(RedPacketDto dto, String redId, List<Integer> list) throws Exception {
        /**
         *
         * 发红包异步的方式
         *
         * 红包记录，异步的方式
         * dto 红包的总金额+个数
         *
         * redId 红包全局唯一标识符
         *
         * list红包随机金额列表
         *
         */
        //定义实体类对象
        Record record = new Record();
        //设置字段信息
        record.setUserId(dto.getUserId());
        record.setRedPacket(redId);
        record.setToal(dto.getTotal());
        record.setAmount(BigDecimal.valueOf(dto.getAmount()));
        record.setCreateTime(new Date());
        //将对象信息插入数据库
        recordMapper.insert(record);
        //定义红包随机金额明细实体类对象
        Detail detail;
        //遍历随机列表，将金额等信息设置到对应的字段中
        for (Integer i:list){
            detail=new Detail();
            detail.setRecordId(record.getId());
            detail.setAmount(BigDecimal.valueOf(i));
            detail.setCreateTime(new Date());
            //将对象信息插入数据库
            detailMapper.insert(detail);
        }



    }

    @Override
    @Async
    public void recordRobRedPacket(Integer userId, String redId, BigDecimal amount) throws Exception {
       //定义记录抢到红包时录入相关信息的实体对象，并设置相应的字段取值
        RobRecord record = new RobRecord();
        record.setAmount(amount);//设置抢到的金额
        record.setUserId(userId);//设置用户id
        record.setRedPacket(redId);//设置红包唯一标识串
        record.setRobTime(new Date());//设置抢到的时间
        //将实体对象信息插入数据库中
        robRecordMapper.insert(record);
    }
}
